package com.atguigu.auth.service.impl;

import com.atguigu.auth.mapper.SysRoleMapper;
import com.atguigu.auth.service.SysRoleService;
import com.atguigu.auth.service.SysUserRoleService;
import com.atguigu.model.system.SysRole;
import com.atguigu.model.system.SysUserRole;
import com.atguigu.vo.system.AssginRoleVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * ClassName:SysRoleServiceImpl
 * Package:com.atguigu.auth.service.Imp
 * Description:
 *
 * @Author:小飞机
 * @Create：2023/5/5 - 8:48
 * @Version: v1.0
 *
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    private SysUserRoleService sysUserRoleService;

    // //查询所用角色 和当前所属的角色
    @Override
    public Map<String, Object> findRoleDataById(Long userId) {
       //1.查询所用角色，返回list集合
        List<SysRole> allRoleList = baseMapper.selectList(null);
        //2.在用户角色表中，根据userId查询角色Id
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId,userId);
        List<SysUserRole> existUserRoleList = sysUserRoleService.list(wrapper);

        //查询的对应的角色所有的获取角色id
        List<Long> existRoleList =
                existUserRoleList.stream().map(c -> c.getRoleId()).collect(Collectors.toList());
        //3.根据角色id查询角色信息
        List<SysRole> assignRoleList = new ArrayList<>();
        for (SysRole a : allRoleList){

            if(existRoleList.contains(a.getId())){
                assignRoleList.add(a);
            }

        }
        //4.把得到的两部分数据放到map集合里面，返回
        Map<String, Object> roleMap = new HashMap<>();
        roleMap.put("assginRoleList", assignRoleList);
        roleMap.put("allRolesList", allRoleList);
        return roleMap;

    }
    //为用户分配角色
    @Override
    public void doAssign(AssginRoleVo assginRoleVo) {
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper();
        wrapper.eq(SysUserRole::getUserId,assginRoleVo.getUserId());
        sysUserRoleService.remove(wrapper);
    //重新分配
        List<Long> roleIdList = assginRoleVo.getRoleIdList();
        for (Long roleId: roleIdList){
            if(StringUtils.isEmpty(roleId)){
                continue;
            }
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(roleId);
            sysUserRole.setUserId(assginRoleVo.getUserId());
            sysUserRoleService.save(sysUserRole);
        }
    }
}
